<script setup>
import { computed, ref } from 'vue'
import { useUserStore } from '@/store/user'
import {
  preventDuplicateLogin,
  withWxRetry,
} from '@/utils/wechat-error-handler'

// Props
const props = defineProps({
  buttonText: {
    type: String,
    default: '微信登录',
  },
  loadingText: {
    type: String,
    default: '登录中...',
  },
  disabled: {
    type: Boolean,
    default: false,
  },
  showError: {
    type: Boolean,
    default: true,
  },
})

// Emits
const emit = defineEmits(['success', 'error', 'start'])

// Store
const userStore = useUserStore()

// State
const isLoading = ref(false)
const errorMessage = ref('')

// Computed
const isDisabled = computed(() => props.disabled || isLoading.value)

// 获取用户信息（兼容新旧版本）
function getUserProfile() {
  return new Promise((resolve, reject) => {
    if (uni.getUserProfile) {
      uni.getUserProfile({
        desc: '用于完善用户资料',
        success: (res) => {
          resolve({
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            country: res.userInfo.country,
            province: res.userInfo.province,
            city: res.userInfo.city,
            language: res.userInfo.language,
          })
        },
        fail: reject,
      })
    }
    else {
      uni.getUserInfo({
        success: (res) => {
          resolve({
            nickName: res.userInfo.nickName,
            avatarUrl: res.userInfo.avatarUrl,
            gender: res.userInfo.gender,
            country: res.userInfo.country,
            province: res.userInfo.province,
            city: res.userInfo.city,
            language: res.userInfo.language,
          })
        },
        fail: reject,
      })
    }
  })
}

// 获取设备信息
function getDeviceInfo() {
  try {
    const systemInfo = uni.getSystemInfoSync()
    return `${systemInfo.platform}_${systemInfo.system}_${systemInfo.model}`
  }
  catch (error) {
    return 'unknown_device'
  }
}

// 微信登录处理
const handleLogin = preventDuplicateLogin(async () => {
  // #ifdef MP-WEIXIN
  try {
    isLoading.value = true
    errorMessage.value = ''
    emit('start')

    // 1. 获取微信登录凭证
    const loginRes = await withWxRetry(async () => {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: 'weixin',
          success: (res) => {
            if (res.errMsg === 'login:ok') {
              resolve(res)
            }
            else {
              reject(new Error(res.errMsg || '获取微信登录凭证失败'))
            }
          },
          fail: reject,
        })
      })
    })

    // 2. 获取用户信息
    const userProfile = await getUserProfile()

    // 3. 调用登录API
    const result = await withWxRetry(async () => {
      return userStore.wxLogin({
        code: loginRes.code,
        userInfo: userProfile,
        deviceInfo: getDeviceInfo(),
      })
    })

    // 4. 登录成功
    isLoading.value = false
    emit('success', result)
  }
  catch (error) {
    isLoading.value = false

    // 显示错误信息
    if (props.showError) {
      errorMessage.value = error.message || '微信登录失败'

      // 3秒后清除错误信息
      setTimeout(() => {
        errorMessage.value = ''
      }, 3000)
    }

    emit('error', error)
  }
  // #endif
})

// 清除错误信息
function clearError() {
  errorMessage.value = ''
}

// 暴露方法
defineExpose({
  handleLogin,
  clearError,
  isLoading: computed(() => isLoading.value),
})
</script>

<template>
  <view class="wechat-login-container">
    <!-- 微信登录按钮 -->
    <!-- #ifdef MP-WEIXIN -->
    <button
      class="wechat-login-btn"
      :class="{ loading: isLoading, disabled: isDisabled }"
      :disabled="isDisabled"
      @click="handleLogin"
    >
      <view class="btn-content">
        <!-- 加载状态 -->
        <view v-if="isLoading" class="loading-icon">
          <view class="spinner" />
        </view>

        <!-- 微信图标 -->
        <uni-icons
          v-else
          type="weixin"
          size="24"
          color="#fff"
          class="wechat-icon"
        />

        <!-- 按钮文字 -->
        <text class="btn-text">
          {{ isLoading ? loadingText : buttonText }}
        </text>
      </view>
    </button>
    <!-- #endif -->

    <!-- 非微信环境提示 -->
    <!-- #ifndef MP-WEIXIN -->
    <view class="not-wechat-tip">
      <uni-icons type="info" size="20" color="#999" />
      <text class="tip-text">
        微信登录功能仅在微信小程序中可用
      </text>
    </view>
    <!-- #endif -->

    <!-- 错误提示 -->
    <view v-if="errorMessage" class="error-tip">
      <uni-icons type="closeempty" size="16" color="#ff4757" />
      <text class="error-text">
        {{ errorMessage }}
      </text>
    </view>
  </view>
</template>

<style lang="scss" scoped>
.wechat-login-container {
  width: 100%;
}

.wechat-login-btn {
  width: 100%;
  height: 50px;
  background: linear-gradient(135deg, #07c160 0%, #06ad56 100%);
  border: none;
  border-radius: 25px;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s ease;
  box-shadow: 0 4px 12px rgba(7, 193, 96, 0.3);

  &:not(.disabled):active {
    transform: scale(0.98);
    box-shadow: 0 2px 8px rgba(7, 193, 96, 0.4);
  }

  &.loading {
    background: linear-gradient(135deg, #06ad56 0%, #059c4f 100%);
  }

  &.disabled {
    opacity: 0.6;
    cursor: not-allowed;
  }

  &::after {
    border: none;
  }
}

.btn-content {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
}

.wechat-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.btn-text {
  color: #fff;
  font-size: 16px;
  font-weight: 500;
}

.loading-icon {
  display: flex;
  align-items: center;
  justify-content: center;
}

.spinner {
  width: 20px;
  height: 20px;
  border: 2px solid rgba(255, 255, 255, 0.3);
  border-top: 2px solid #fff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.not-wechat-tip {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  padding: 15px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.tip-text {
  color: #666;
  font-size: 14px;
}

.error-tip {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-top: 10px;
  padding: 8px 12px;
  background: #fff5f5;
  border: 1px solid #fed7d7;
  border-radius: 6px;
  animation: fadeIn 0.3s ease;
}

.error-text {
  color: #ff4757;
  font-size: 12px;
  flex: 1;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}
</style>
